package com.zheng.handler;


import com.zheng.client.RPCConsumer;
import com.zheng.zk.Curator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.Random;
import java.util.concurrent.Callable;

/**
 *  @author: zheng
 *  @Date: 2020-06-28 23:10
 *  @Description:自定义事件处理器
 */
public class UserClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    //1.定义成员变量
    private ChannelHandlerContext context;//事件处理上下文对象
    private String result;//记录服务器返回的数据
    private Object param;//给服务器传递的数据
    private long startTime;
    private long endTime;
    private String path;
    private String host;
    private Integer port;


    public UserClientHandler(String path,String host,Integer port){
        this.path=path;
        this.host=host;
        this.port=port;
    }
    //2.实现channelActive 客户端和服务端的连接,该方法自动执行
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //初始化ChannelHandlerContext
        this.context=ctx;
    }

    //3.读取服务器的数据，该方法自动执行
    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result=msg.toString();
        //计算请求时间
        endTime=System.currentTimeMillis();
        //更新节点数据
        long time=endTime-startTime;
        if(time==0){
            time=new Random().nextInt(10);
        }
        String data="host:"+host+":port:"+port+":"+time;
        Curator.getCuratorFramework().setData().forPath("/"+path,data.getBytes());

    }

    @Override
    public synchronized Object call() throws Exception {
        //context 给服务器写数据

        context.writeAndFlush(param);
        startTime=System.currentTimeMillis();

        return result;
    }



    public void setParam(Object param) {
        this.param = param;
    }


}
